import {
	request
} from '@/utils/request';
import moment from 'moment';

const genMapKey = (state, message) => {
	const userInfo = state.userInfo;
	const userId = userInfo.userId;
	const {
		fromId,
		toId
	} = message;
	if (userId === fromId) {
		return `#${toId}#`;
	}
	return `#${fromId}#`;
}

const state = {
	hasLogin: false, //是否已经连接 websocket
	userInfo: {
		accountHead: '/img/person/default_head3.png'
	},
	hasBindPhone: false,
	chatListInfo: {
		list: [],
		pageNum: 1,
		pageSize: 10
	},
	chatFeeListInfo: {
		list: [],
		pageNum: 1,
		pageSize: 10
	},
	currentChatPerson: {
		accountHead: '/img/person/default_head3.png'
	},
	messageMap: new Map(),

	messageFeeMap: new Map(),
	// 系统通知
	hasSysMessage: false,
	chatLastPage: false, //聊天是否是最后一页
	chatFeeLastPage: false, //专家聊天是否是最后一页
}

const parseMsg = content=>{
	console.log('parseMsg content ', content);
	if(content.indexOf('<img')!==-1){
		const obj = JSON.parse(content);
		console.log('parseMsg obj ',obj);
		return {
			note: obj,
			type:'image',
		};
	}
	return {
		note:content,
		type:'text'
	};
}

const actions = {
	pushLoginMessage({
		state
	}, payload) {
		request.get({
			url: 'sysMessage/pushLoginMessage',
			data: payload
		}).then(res => {}, res => {})
	},
	sendFeeMsg({
		commit,
		state
	}, payload) {
		request.post({
			url: 'expertMsg/send',
			data: payload
		}).then(res => {

		}, res => {})
	},
	get_user_by_id({
		commit,
		state
	}, payload, cb) {
		const callback = payload.cb;
		delete payload.cb;
		request.get({
			url: 'user/getUserInfoById',
			data: payload
		}).then(res => {
			commit('setCurrentPerson', res);
			callback && callback();
		}, res => {})
	},
	// 付费咨询 聊天信息
	get_chat_fee_list({
		commit,
		state
	}, payload) {
		const callback = payload.cb;
		delete payload.cb;
		request.get({
			url: 'expertMsg/getHistory',
			data: payload
		}).then(res => {
			commit('setChatFeeHistory', res);
			callback && callback();
		}, res => {
			// commit('setChatLogin', false);
		})
	},
	get_chat_contact_list({
		commit,
		state
	}, payload) {
		request.get({
			url: 'im/get_userinfo',
			data: payload
		}).then(res => {
			commit('setUserInfo', res.userInfo);
		}, res => {
			commit('setChatLogin', false);
		})
	},
	sendMsg({
		commit,
		state
	}, payload) {
		let that = this;
		getApp().globalData.socket.sendSocketMessage(payload);
	},
	loadChatList({
		commit,
		state
	}, payload) {
		let cb = payload.cb;
		if (cb) {
			delete payload.cb;
		}
		request.get({
			url: 'im/get_histrecord',
			data: payload
		}).then(res => {
			console.log(res.messageList)
			commit('setChatHistory', res.messageList)
			cb && cb();
		}, res => {})
	}
};

const compareDate = (a, b) => {
	var value1 = new Date(moment(a.sendTime).format());
	var value2 = new Date(moment(b.sendTime).format());
	return value1 - value2;
}

const compareFeeDate = (a, b) => {
	var value1 = new Date(moment(a.createDate).format());
	var value2 = new Date(moment(b.createDate).format());
	return value1 - value2;
}

//判断是否为今天
const isToday = (time) => {
	if (new Date() - new Date(moment(time).format()) < 86400000) {
		return moment(time).format('HH:mm')
	} else {
		return moment(time).format('MM/DD HH:mm')
	}
}

const getters = {
	currentMsgList(state, getters) {
		return id => {
			const list = state.messageMap.get(`#${id}#`) || [];
			let time = '' //记录时间
			let temp = [] //临时数组

			if (list.length > 0) {
				time = new Date(moment(list[0].sendTime).format())
				//插入首个时间
				temp.push({
					'type': 'time',
					'time': isToday(list[0].sendTime)
				})
				for (let k of list) {
					if (typeof k.content == 'string') {
						try {
							k.content = JSON.parse(k.content)
							if (typeof k.content == 'number') {
								k.content = JSON.stringify(k.content)
							}

						} catch (e) {

						}
					}


					if (new Date(moment(k.sendTime).format()) - time > 600000) {
						time = new Date(moment(k.sendTime).format())
						temp.push({
							'type': 'time',
							'time': isToday(k.sendTime)
						})
						temp.push(k)
					} else {
						temp.push(k)
					}
				}
			}
			return temp
		}
	},
	currentFeeMsgList(state, getters) {
		return id => {
			const list = state.messageFeeMap.get(`#${id}#`) || [];
			let time = '' //记录时间
			let temp = [] //临时数组
			if (list.length > 0) {
				time = new Date(moment(list[0].createDate).format())
				//插入首个时间
				temp.push({
					'type': 'time',
					'time': isToday(list[0].createDate)
				})
				for (let k of list) {
					if (new Date(moment(k.createDate).format()) - time > 600000) {
						time = new Date(moment(k.createDate).format())
						temp.push({
							'type': 'time',
							'time': isToday(k.createDate)
						})
						temp.push(k)
					} else {
						temp.push(k)
					}
				}
			}
			return temp
		}
	},
	histChatList(state, getters) {
		if (state.userInfo) {
			if (state.userInfo.histChatList) {
				return state.userInfo.histChatList.filter(c => c.userId !== state.userInfo.userId);
			}
		}
		return [];
	},
}

const mutations = {
	clearSysMessage(state, payload) {
		state.hasSysMessage = false;
	},
	// 及时聊天数据处理
	handleMessage(state, payload) {
		// 心跳消息    
		const type = payload && payload.type;
		if (type === "REGISTER") {
			//连接聊天服务器成功
			console.log('handleMessage 聊天注册成功', payload);
			state.hasLogin = true;
			getApp().globalData.chatLogin = true;
		} else if (type === 'SINGLE_SENDING') {
			const userInfo = state.userInfo;
			let mapKey = '';
			// 单聊消息
			const {
				fromUserId,
				toUserId
			} = payload;
			mapKey = genMapKey(state, {
				fromId: fromUserId,
				toId: toUserId
			});
			const messageMap = state.messageMap;
			const messages = messageMap.get(mapKey);
			console.log(messages)
			if (messages) {
				messages.push(payload);
			} else {
				messageMap.set(mapKey, [payload])
			}
			const mapNew = new Map();
			mapNew.set(mapKey, messageMap.get(mapKey));
			state.messageMap = mapNew;
			console.log('handleMessage 单聊消息', messageMap);
		} else if (type === "SYSTEM_MSG_NOTICE") {
			// 通知消息
			state.hasSysMessage = true;
		} else if (type === 'PAY_INQUIRE_SENDING') {
			//付费咨询
			const userInfo = state.userInfo;
			let mapKey = '';
			// 单聊消息
			const {
				fromUserId,
				toUserId,
				msgId,
				content,
				type
			} = payload;
			mapKey = genMapKey(state, {
				fromId: fromUserId,
				toId: toUserId,
			});
			const messageMap = state.messageFeeMap;
			const messages = messageMap.get(mapKey);
			console.log(messages);
			const {note, type:msgType} = parseMsg(content);
			const comingMsg = {
				note,
				type:msgType
			}
			if (messages) {
				messages.push(comingMsg);
			} else {
				messageMap.set(mapKey, [comingMsg])
			}
			const mapNew = new Map();
			mapNew.set(mapKey, messageMap.get(mapKey));
			state.messageFeeMap = mapNew;
		}
	},
	setChatLogin(state, loginState = true) {
		state.hasLogin = loginState;
	},
	setUserInfo(state, userInfo) {
		state.userInfo = userInfo;
	},
	setCurrentPerson(state, p) {
		state.currentChatPerson = p;
	},
	setChatFeeHistory(state, data) {
		//存储是否是最后一页
		state.chatFeeLastPage = data.isLastPage
		let messages = data.list;
		//时间排序 升序排序用于展示
		messages.sort(compareFeeDate);
		const userInfo = state.userInfo;
		let mapKey = '';
		const mapNew = new Map();
		if (messages.length !== 0) {
			let firMsg = messages[0];
			console.log('firMsg ', firMsg);
			const params = {
				fromId: firMsg.expertInfoId,
				toId: firMsg.userInfoId
			}
			mapKey = genMapKey(state, params);
			//非首页时合并分页数据
			if (!data.isFirstPage) {
				let temp = []
				temp = state.messageFeeMap.get(mapKey) || []
				messages = [...messages, ...temp]
			}

			mapNew.set(mapKey, messages);
			state.messageFeeMap = mapNew;
		}
		console.log('mapNew', mapNew);
	},
	setChatHistory(state, data) {
		//存储是否是最后一页
		state.chatLastPage = data.isLastPage
		let messages = data.list;
		//时间排序 升序排序用于展示
		messages.sort(compareDate);
		const userInfo = state.userInfo;
		let mapKey = '';
		const mapNew = new Map();
		if (messages.length !== 0) {
			let firMsg = messages[0];
			mapKey = genMapKey(state, firMsg);
			//非首页时合并分页数据
			if (!data.isFirstPage) {
				let temp = []
				temp = state.messageMap.get(mapKey) || []
				messages = [...messages, ...temp]
			}
			mapNew.set(mapKey, messages);
			state.messageMap = mapNew;
		}
	},
	appendChatData(state, message) {
		const userInfo = state.userInfo;
		const {
			fromId,
			toId
		} = message;
		const mapKey = genMapKey(state, message);
		const mapNew = new Map();
		const old_messages = state.messageMap.get(mapKey);
		if (old_messages) {
			old_messages.push(message);
			mapNew.set(mapKey, old_messages);
		} else {
			mapNew.set(mapKey, [message]);
		}
		state.messageMap = mapNew;
	},
	appendFeeChatData(state, message) {
		const userInfo = state.userInfo;
		const {
			fromId,
			toId,
			content,
			sendTime
		} = message;
		const mapKey = genMapKey(state, message);
		const mapNew = new Map();
		message.userInfoId = fromId;
		message.expertInfoId = toId;
		message.createDate = sendTime;
		message.note = content;
		const old_messages = state.messageFeeMap.get(mapKey);
		if (old_messages) {
			old_messages.push(message);
			mapNew.set(mapKey, old_messages);
		} else {
			mapNew.set(mapKey, [message]);
		}
		state.messageFeeMap = mapNew;
		console.log('appendFeeChatData message ', message);
	},
	appendFeeChatAnswerData(state, message) {
		const userInfo = state.userInfo;
		const {
			fromId,
			toId,
			content,
			sendTime
		} = message;
		const mapKey = genMapKey(state, message);
		const mapNew = new Map();
		message.userInfoId = toId;
		message.expertInfoId = fromId;
		message.createDate = sendTime;
		message.note = content;
		const old_messages = state.messageFeeMap.get(mapKey);
		if (old_messages) {
			old_messages.push(message);
			mapNew.set(mapKey, old_messages);
		} else {
			mapNew.set(mapKey, [message]);
		}
		state.messageFeeMap = mapNew;
	}
}

export default {
	namespaced: true,
	state,
	actions,
	getters,
	mutations
}
